﻿using Hetang.Models.Authorize;
using Hetang.Models.DataContext;
using Hetang.Models.Classes;
using Hetang.Models.Helper;
using Hetang.Models.Interface;
using Hetang.Models.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace Hetang.Controllers
{
    public class SignupController : Controller
    {
        IDatabaseRepository _dr;

        public SignupController() : this(new DatabaseRepository()) { }

        public SignupController(IDatabaseRepository dr)
        {
            _dr = dr;
        }

        public ActionResult Index()
        {
            if (this.Request.IsAuthenticated)
                return RedirectToAction("index", "home", new { area = "" });
            return View();
        }

        [HttpPost]
        public ActionResult Index(dt_Signup signup)
        {
            if (ModelState.IsValid)
            {
                if (signup.agree)
                {
                    try
                    {
                        tbl_Account ac = new tbl_Account()
                        {
                            Add_Date = DateTime.Now,
                            Email = signup.email.Trim(),
                            Head_Path = string.Empty,
                            Password = FormsAuthentication.HashPasswordForStoringInConfigFile(signup.password, "MD5"),
                            Sina_Account_Id = string.Empty,
                            User_Type = signup.usertype.Equals("company") ? "company" : "person",
                            UserName = signup.username
                        };

                        _dr.CreateAccount(ac);

                        return RedirectToAction("index", "home", new { area = "" });
                    }
                    catch
                    {
                        TempData.Add("Error", "系统有点忙，等一下再注册吧！");
                    }
                }
                else
                {
                    ModelState.AddModelError("agree", "↖先同意协议才可继续进行注册。");
                }
            }
            return View();
        }
    }
}